package sample.ws.util;

import org.apache.cxf.staxutils.StaxUtils;

import javax.xml.namespace.QName;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Service;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * WsClient..
 *
 * @author Lizhong
 * @date 2019/7/13
 */
public class WsClient {
    public static String sendRequest(String serviceUrl, String namespace, String localPart, String serviceName ,String request) {


        // String request = "<q0:getMetaData xmlns:q0=\"http://www.ssii.com.cn/\"><name>Elan</name><token>66</token> <page>1</page><size>10</size></q0:getMetaData>";

        StreamSource source = new StreamSource(new StringReader(request));
        Service service = null;
        try {
            service = Service.create(new URL(serviceUrl + "?wsdl"),
                    new QName(namespace, serviceName));
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        Dispatch<Source> disp = service.createDispatch(
                new QName(namespace, localPart), Source.class, Service.Mode.PAYLOAD);

        Source result = disp.invoke(source);
        String resultAsString = StaxUtils.toString(result);
        System.out.println(resultAsString);
        return resultAsString;

    }
}
